import {
  exportExcelFile,
  getInterface,
  resetForm,
} from "@/common/utils/GlobalUtils";
import { reactive, ref } from "vue";

/**
 * table的公共方法
 * @param {Object} interfaceConfig - 获取 table 时所要调用接口的信息
 * - @param {String} fileName - 所要调用接口的文件名称（@/api 下的 js 文件名称）。如：@/api/businessFinance.js ，此处传 'businessFinance'
 * - @param {String} apiPath - 所要调用接口的路径（fileName 文件夹中的具体对象名称）。如：businessFinance.js 文件中的 'bankManagementApi.getInterestPageList'
 * @param exportConfig  - 导出 table 时所要调用接口的参数配置。各参数解释见：GlobalUtils.js -> getInterface() 方法
 * @param {Object} defaultParameters - 默认参数
 */
export const tableCommonFun = (
  interfaceConfig = { fileName: "", apiPath: "" },
  exportConfig = { fileName: "", apiPath: "", tableName: "" },
  defaultParameters
) => {
  // 查询条件
  const form = ref({});
  const page = reactive({
    total: 0,
    current: 1,
    size: 50,
  });
  const tableOption = ref([]);
  const tableData = ref([]);
  const selectedArr = ref([]);

  /**
   * 获取数据
   * @param param 传给后端的参数
   */
  const getData = (param, callback) => {
    getInterface(interfaceConfig.fileName, interfaceConfig.apiPath, param).then(
      (res) => {
        if (res.code === "200") {
          if (callback) callback(res);
          tableData.value = res.data.content;
          page.total = res.data.totalSize;
        }
      }
    );
  };

  /**
   * 表单查询方法
   *
   */
  const onQuery = () => {
    page.current = 1;
    page.size = 50;
    let param = {
      param: {
        ...defaultParameters,
        ...form.value,
      },
      pageNum: page.current,
      pageSize: page.size,
    };
    getData(param);
  };

  /**
   * 重置表单
   *
   */
  const onReset = () => {
    resetForm(form.value);
    console.log('form.value', form);
    page.current = 1;
    page.size = 50;
    let param = {
      pageNum: page.current,
      pageSize: page.size,
      param: { ...defaultParameters }
    };
    getData(param);
  };

  /**
   * 页数和页面改变时触发
   * @param e 页码和页面参数
   */
  const onPageChange = (e) => {
    page.current = e.page;
    page.size = e.limit;
    let param = {
      param: {
        ...defaultParameters,
        ...form.value,
      },
      pageNum: page.current,
      pageSize: page.size,
    };
    getData(param);
  };

  /**
   * 多选/或者单选时触发
   * @param e 回调参数
   */
  const handleSelectionChange = (e) => {
    selectedArr.value = e;
  };

  /**
   * 导出列表数据
   *
   */
  const onExport = () => {
    getInterface(exportConfig.fileName, exportConfig.apiPath, form.value).then(
      (res) => {
        if (res) {
          exportExcelFile(res, exportConfig.tableName);
        }
      }
    );
  };

  return {
    form,
    page,
    tableOption,
    tableData,
    selectedArr,
    onQuery,
    onReset,
    onPageChange,
    getData,
    handleSelectionChange,
    onExport,
  };
};
